import '../../index.dart';

//  强
const strong = r"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,18}$";
//  中
const middle =
    r"^(?=.{8,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$";
//  弱
const weak = r"(?=.{8,}).*";

class ResetPasswordsPage extends StatefulWidget {
  const ResetPasswordsPage({Key? key}) : super(key: key);

  @override
  _ResetPasswordsState createState() => _ResetPasswordsState();
}

class _ResetPasswordsState extends State<ResetPasswordsPage> {
  //表单状态
  final _formKey = GlobalKey<FormState>();

  //焦点
  final FocusNode _focusPresent = FocusNode();
  final FocusNode _focusNewPas = FocusNode();
  final FocusNode _focusNewPass = FocusNode();

  //输入框控制器
  final TextEditingController _presentController = TextEditingController();
  final TextEditingController _newPasController = TextEditingController();
  final TextEditingController _newPassController = TextEditingController();

  bool _isPresent = true;
  bool _isNewPas = true;
  bool _isNewPass = true;

  bool _isPresentError = true;
  String _isPresentName = '';

  bool _isNewPasError = true;
  String _isNewPasErrorName = '';

  bool _isError = true;
  String _isErrorName = '';

  int _strong = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GlobalStyle(
      child: BackgroundStyleWidget(
          child: Scaffold(
              backgroundColor: Theme.of(context).colorScheme.surface,
              appBar: AppBar(
                leading: IconButton(
                  icon: Image.asset('images/common_left.png',
                      width: 16, height: 16),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                title: const Text('重置密码'),
                centerTitle: true,
              ),
              body: _bodyView())),
    );
  }

  Widget _bodyView() {
    return SingleChildScrollView(
      child: Column(
        children: [
          const SizedBox(height: 10),
          Container(
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.background,
            ),
            child: Column(
              children: [
                Stack(
                  children: [
                    _input(_presentController, _isPresent, '当前密码', (value) {
                      setState(() {
                        _isPresent = value.isEmpty ? true : false;
                        if (value.trim().isNotEmpty) {
                          _isPresentError = true;
                        }
                      });
                    }),
                    _errorHint(_isPresentError, _isPresentName)
                  ],
                ),
                _sizeBox(),
                Stack(
                  children: [
                    Padding(
                        padding: const EdgeInsets.fromLTRB(16, 5, 16, 20),
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Flexible(
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.center,
                                    children: [
                                      Image.asset('images/me_password.png',
                                          width: 20, height: 20),
                                      const SizedBox(width: 5),
                                      Flexible(
                                        // width: 200,
                                        // height: 20,
                                        child: TextField(
                                          controller: _newPasController,
                                          decoration: InputDecoration(
                                            contentPadding:
                                                EdgeInsets.symmetric(
                                                    horizontal: 10,
                                                    vertical: 0),
                                            hintText: '新登录密码',
                                            // hintStyle: themeData
                                            //     .textTheme.titleMedium
                                            //     ?.copyWith(
                                            //         color: themeData.colorScheme
                                            //             .onSurface),
                                            border: OutlineInputBorder(
                                                borderSide: BorderSide.none),
                                          ),
                                          onChanged: (value) {
                                            _newPas(value);
                                          },
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                                _clearInput(_isNewPas, () {
                                  setState(() {
                                    _newPasController.text = '';
                                    _isNewPas = true;
                                    _isNewPasError = true;
                                    _strong = 0;
                                  });
                                }),
                              ],
                            ),
                            // const SizedBox(height: 6),
                            _sizeBox(),
                            const SizedBox(height: 6),
                            _colorList(_strong)
                          ],
                        )),
                    _errorHint(_isNewPasError, _isNewPasErrorName)
                  ],
                ),
                _sizeBox(),
                Stack(
                  children: [
                    _input(_newPassController, _isNewPass, '请输入新密码', (value) {
                      setState(() {
                        _isNewPass = value.isEmpty ? true : false;
                        if (value != _newPasController.text) {
                          _isError = false;
                          _isErrorName = '两次输入的密码不一致';
                        } else {
                          _isError = true;
                        }
                      });
                    }),
                    _errorHint(_isError, _isErrorName)
                  ],
                )
              ],
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: 10,
              ),
              Padding(
                padding: EdgeInsets.only(top: 4),
                child: Text('*',
                    textAlign: TextAlign.center,
                    style: Theme.of(context)
                        .textTheme
                        .labelMedium
                        ?.copyWith(color: Theme.of(context).colorScheme.error)),
              ),
              SizedBox(
                width: 5,
              ),
              Expanded(
                child: Text(
                  '密码由8-18位字母、数字、符号组成，区分大小写密码不能包含弱口令：如abc,123,111等简单数字、字母',
                  style: Theme.of(context).textTheme.labelMedium?.copyWith(
                        color: Theme.of(context).colorScheme.onSecondary,
                      ),
                ),
              ),
              SizedBox(
                width: 10,
              ),
            ],
          ),
          SizedBox(
              width: double.infinity,
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: CommonButton.elevatedButton(context, text: "确定",
                onPressed: () {
                  setState(() {
                    if (!_presentController.text.isNotEmpty) {
                      _isPresentError = false;
                      _isPresentName = '请输入当前密码';
                      return;
                    }
                    if (!_newPasController.text.isNotEmpty) {
                      _isNewPasError = false;
                      _isNewPasErrorName = '请输入新密码';
                      return;
                    }
                    if (!_newPassController.text.isNotEmpty) {
                      _isError = false;
                      _isErrorName = '请输入新密码';
                      return;
                    }
                    if (!_isNewPasError || !_isError) {
                      return;
                    }
                    _submitAjax();
                  });
                }),
              ))
        ],
      ),
    );
  }

  /// 输入框
  /// controller 输入控制器
  /// state 是否显示清楚
  /// name 输入框
  /// fn 回调
  Widget _input(controller, state, name, fn) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 5, 16, 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Flexible(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Image.asset('images/me_password.png', width: 20, height: 20),
                const SizedBox(width: 5),
                Flexible(
                  // width: 200,
                  // height: 20,
                  child: TextField(
                    controller: controller,
                    decoration: InputDecoration(
                      contentPadding: const EdgeInsets.symmetric(
                          horizontal: 10, vertical: 0),
                      hintText: name,
                      // hintStyle: const TextStyle(
                      // color: Color.fromRGBO(209, 209, 209, 1)),
                      border:
                          const OutlineInputBorder(borderSide: BorderSide.none),
                    ),
                    onChanged: (value) {
                      fn(value);
                    },
                  ),
                )
              ],
            ),
          ),
          _clearInput(state, () {
            setState(() {
              controller.text = '';
              state = true;
            });
          }),
        ],
      ),
    );
  }

  /// 错误提示
  /// state 是否显示
  /// name 提示文本
  Widget _errorHint(state, name) {
    return Positioned(
      left: 50,
      bottom: 0,
      child: Offstage(
        offstage: state,
        child: Text(
          name,
          style: Theme.of(context)
              .textTheme
              .bodyMedium
              ?.copyWith(color: Theme.of(context).colorScheme.error),
        ),
      ),
    );
  }

  /// 清除
  /// state 是否显示
  /// fn 回调
  Widget _clearInput(state, fn) {
    return GestureDetector(
        onTap: fn,
        child: Offstage(
          offstage: state,
          child: Image.asset('images/common_close.png', width: 12, height: 12),
        ));
  }

  /// 分割线
  Widget _sizeBox() {
    return SizedBox(
      width: double.infinity,
      height: 1,
      child: DecoratedBox(
        decoration: BoxDecoration(color: Theme.of(context).colorScheme.surface),
      ),
    );
  }

  /// 密码强弱
  Widget _colorList(strong) {
    if (strong == 1) {
      return Row(
        children: [
          const SizedBox(width: 12),
          _strength('弱', _color(1)),
          const SizedBox(width: 10),
          _strength('中', _color(0)),
          const SizedBox(width: 10),
          _strength('强', _color(0)),
        ],
      );
    }
    if (strong == 2) {
      return Row(
        children: [
          const SizedBox(width: 12),
          _strength('弱', _color(2)),
          const SizedBox(width: 10),
          _strength('中', _color(2)),
          const SizedBox(width: 10),
          _strength('强', _color(0)),
        ],
      );
    }
    if (strong == 3) {
      return Row(
        children: [
          const SizedBox(width: 12),
          _strength('弱', _color(3)),
          const SizedBox(width: 10),
          _strength('中', _color(3)),
          const SizedBox(width: 10),
          _strength('强', _color(3)),
        ],
      );
    }
    return Row(
      children: [
        const SizedBox(width: 12),
        _strength('弱', _color(0)),
        const SizedBox(width: 10),
        _strength('中', _color(0)),
        const SizedBox(width: 10),
        _strength('强', _color(0)),
      ],
    );
  }

  /// 密码强度
  /// name 文本
  /// state 状态
  Widget _strength(name, colors) {
    return Row(
      children: [
        Container(
          width: 66,
          height: 4,
          decoration: BoxDecoration(
            gradient: LinearGradient(
                //渐变位置
                begin: Alignment.bottomLeft, //右上
                end: Alignment.topRight, //左下
                stops: [0.0, 1.0], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: colors),
            borderRadius: BorderRadius.circular((12)),
          ),
        ),
        SizedBox(width: 10),
        Container(
          width: 18,
          height: 18,
          alignment: Alignment.center,
          child: Text(name, style: TextStyle(color: Colors.white, fontSize: 9)),
          decoration: BoxDecoration(
            gradient: LinearGradient(
                //渐变位置
                begin: Alignment.topLeft, //右上
                end: Alignment.bottomLeft, //左下
                stops: [0.0, 1.0], //[渐变起始点, 渐变结束点]
                //渐变颜色[始点颜色, 结束颜色]
                colors: colors),
            borderRadius: BorderRadius.circular((12)),
          ),
        )
      ],
    );
  }

  /// 密码强弱
  List<Color> _color(value) {
    if (value == 1) {
      return const [
        Color.fromRGBO(255, 165, 168, 1),
        Color.fromRGBO(249, 63, 69, 1)
      ];
    }
    if (value == 2) {
      return const [
        Color.fromRGBO(83, 154, 255, 1),
        Color.fromRGBO(3, 48, 255, 1)
      ];
    }
    if (value == 3) {
      return const [
        Color.fromRGBO(83, 255, 214, 1),
        Color.fromRGBO(0, 177, 135, 1)
      ];
    }
    return const [
      Color.fromRGBO(203, 210, 217, 1),
      Color.fromRGBO(135, 135, 135, 1)
    ];
  }

  /// 新登录密码
  void _newPas(value) {
    List<int> valueCodes = value!.codeUnits;
    bool isConsecutive = false;
    for (int i = 0; i < valueCodes.length - 2; i++) {
      //大于等于0且小于等于9 或 大于等于A小于等于Z 或大于等于a小于等于z
      if ((valueCodes[i] >= 48 && valueCodes[i] <= 57) ||
          (valueCodes[i] >= 65 && valueCodes[i] <= 90) ||
          (valueCodes[i] >= 97 && valueCodes[i] <= 122)) {
        //abc or 123
        if (valueCodes[i + 2] - valueCodes[i + 1] == 1 &&
            valueCodes[i + 1] - valueCodes[i] == 1) {
          isConsecutive = true;
          break;
          //aaa or 111
        } else if (valueCodes[i + 2] == valueCodes[i + 1] &&
            valueCodes[i + 1] == valueCodes[i]) {
          isConsecutive = true;
          break;
        }
      }
    }

    //验证是否包含特殊字符
    bool isHaveSpecialCharacters(String input) {
      final reg = RegExp(r'[`~!@#$%^&*()_+=|;:(){}'',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？-]');
      return reg.hasMatch(input);
    }

    setState(() {
      _isNewPas = value.isEmpty ? true : false;
      if (RegExp(weak).firstMatch(value) != null) {
        _strong = 1;
      }
      if (RegExp(middle).firstMatch(value) != null) {
        _strong = 2;
      }
      if (RegExp(strong).firstMatch(value) != null && isHaveSpecialCharacters(value) ) {
        _strong = 3;
      }
      if (value.trim().length < 8) {
        _strong = 0;
      }

      if (value.isEmpty) {
        _isNewPasError = false;
        _isNewPasErrorName = '请输入新密码';
      }
      // else if (isConsecutive) {
      //   _isNewPasError = false;
      //   _isNewPasErrorName = '密码格式错误';
      // }
      else if (value.trim().length < 8 || value.trim().length > 18) {
        _isNewPasError = false;
        _isNewPasErrorName = '密码长度不正确';
      } else if (RegExp(middle).firstMatch(value) == null) {
        _isNewPasError = false;
        _isNewPasErrorName = '密码等级太弱';
      } else {
        _isNewPasError = true;
      }
    });
  }

  /// 重置密码
  void _submitAjax() async {
    try {
      ResponseData responseData = await Api(context).postUpdatePassword(
          _presentController.text,
          _newPasController.text,
          _newPassController.text);
      if (responseData.success) {
        showToast("修改成功");
        Navigator.of(context).pop();
      }else{
        showToast(responseData.msg);
      }
    } catch (e) {
      //失败则提示
      showToast(S.of(context).networkError);
    }
  }
}
